/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mainpackage;

import engine.ani.Animation;
import engine.ani.Player;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.Hashtable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * 资源管理类，对游戏中图片包括本地图片，动画文件包括本地动画文件的管理
 */
public class ResManager {

    /****************************************************avatar管理******************************************************/
    /*
     * 游戏动画文件容器 
     */
    //长驻内存动画文件容器
    public static Hashtable publicResAnis = new Hashtable();
    //同一3×3房间里动画文件容器
    public static Hashtable publicOneRoomResAnis = new Hashtable();
    //临时内存动画文件容器
    public static Hashtable tempResAnis = new Hashtable();
    /*
     * 游戏图片文件容器 
     */
    //长驻内存图片文件容器
    public static Hashtable publicResImgs = new Hashtable();
    //同一3×3房间里图片文件容器
    public static Hashtable publicOneRoomResImgs = new Hashtable();
    //临时内存图片文件容器
    public static Hashtable tempResImgs = new Hashtable();
    //
    //载入资源网络标记
    //网络有动画文件过来
    public static boolean BL_RECEIVE_NET_ANIMATION = false;
    //网路偶有图片过来
    public static boolean BL_RECEIVE_NET_IMAGE = false;

    /*********************************************************动画文件管理*************************************************************************/
    public static Animation loadAnimation(String avatarid, byte type, boolean blsend) {
        return loadAnimation(Integer.parseInt(avatarid), type, blsend);
    }
    //添加avatar 检查是否为本地avatar 如果没有则发送请求

    public static Animation loadAnimation(int avatarid, byte type, boolean blsend) {
        if (avatarid == -1 || avatarid == 0) {
            return null;
        }
        byte atype = Constant.RES_PUBLIC_TEMP;
        if (type == Constant.NET_TYPE_PLAYER_AVATAR_ANI) {
            atype = GameBean.BL_PLAYER_ENTER_CENCE ? Constant.RES_PUBLIC_FINAL : Constant.RES_PUBLIC_TEMP;
        } else if (type == Constant.NET_TYPE_OTHERPLAYER_AVATAR_ANI) {
            atype = Constant.RES_PUBLIC_ONEROOM;
        } else {
            atype = type;
        }
        if (haveAni(avatarid) != -1) {
            return getAnimation(avatarid, haveAni(avatarid));
        }
        Animation ani = new Animation();
        try {
            if (blsend && !Tools.isLocalAvatar(avatarid)) {
                ani.blHaveAni = false;
                ani.iAnimationId = avatarid;
                GameBean.SH_RES_PARAMETER_ONE = type;
                GameBean.SH_RES_PARAMETER_TWO = avatarid;
                MainLogic.netController.setMsgResArray(new String[]{String.valueOf(avatarid)});
                MainLogic.netController.send(Constant.MSG_NET_GET_ANIMATION, Constant.SOCKET_MSG_TYPE_RES);
                return null;
            } else {
                if (ani.loadAnimation(Constant.RES_PATH, atype, null, avatarid)) {
                    putAnimation(atype, avatarid, ani);
                    if (type == Constant.NET_TYPE_OTHERPLAYER_AVATAR_ANI) {
                        Player.blNeedChangeAction = true;
                    }
                } else {
                    ani = null;
                    return null;
                }
                return ani;
            }
        } catch (Exception e) {
            Tools.printLog("添加动画文件异常：" + avatarid);
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
            return ani;
        }
    }

    /*
     * 从网络上获取图片
     */
    public static void loadAnimation(int avatarid, byte type, byte[] aniStream, boolean blsend) {
        try {
            if (haveAni(avatarid) != -1) {
                return;
            }
            byte atype = Constant.RES_PUBLIC_TEMP;
            if (type == Constant.NET_TYPE_PLAYER_AVATAR_ANI) {
                atype = GameBean.BL_PLAYER_ENTER_CENCE ? Constant.RES_PUBLIC_FINAL : Constant.RES_PUBLIC_TEMP;
                if (GameBean.BL_PLAYER_ENTER_CENCE) {
                    MainLogic.getInstance().gamePlayer.changeAction(Constant.PLAYER_STATE_AUTO_RUN, MainLogic.getInstance().gamePlayer.byPlayerDirection, false, true);
                }
//            MainLogic.getInstance().gamePlayer.changeAction(avatarid);
            } else if (type == Constant.NET_TYPE_OTHERPLAYER_AVATAR_ANI) {
                atype = Constant.RES_PUBLIC_ONEROOM;
            } else {
                atype = type;
            }
            Animation ani = new Animation();
            ani.loadAnimation(atype, Constant.RES_PATH, avatarid, new DataInputStream(new ByteArrayInputStream(aniStream)), blsend);
            putAnimation(atype, avatarid, ani);
            if (type == Constant.NET_TYPE_OTHERPLAYER_AVATAR_ANI) {
                Player.blNeedChangeAction = true;
            }
            ani = null;
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }

    private static void putAnimation(byte type, int avatarid, Animation aAnimation) {
//        aAnimation.blHaveAni = true;
        switch (type) {
            case Constant.RES_PUBLIC_FINAL:
                publicResAnis.put(String.valueOf(avatarid), aAnimation);
                break;
            case Constant.RES_PUBLIC_ONEROOM:
                publicOneRoomResAnis.put(String.valueOf(avatarid), aAnimation);
                break;
            case Constant.RES_PUBLIC_TEMP:
                tempResAnis.put(String.valueOf(avatarid), aAnimation);
                break;
        }
    }

    public static Animation getAnimation(String avatarid, byte type) {
        if (avatarid == null || avatarid.equals("")) {
            Tools.printLog("avatarid" + avatarid);
            return null;
        }
        return getAnimation(Integer.parseInt(avatarid), type);
    }

    public static Animation getAnimation(int avatarid, byte type) {
        if (avatarid == -1 || avatarid == 0) {
            return null;
        }
//        if (type == (byte) -1)
        {
            type = haveAni(avatarid);
        }
        switch (type) {
            case Constant.RES_PUBLIC_FINAL:
                return (Animation) publicResAnis.get(String.valueOf(avatarid));
            case Constant.RES_PUBLIC_ONEROOM:
                return (Animation) publicOneRoomResAnis.get(String.valueOf(avatarid));
            case Constant.RES_PUBLIC_TEMP:
                return (Animation) tempResAnis.get(String.valueOf(avatarid));
        }
        return null;
    }
    /*
     * 是否有这个动画文件
     */

    public static byte haveAni(String aniid) {
        return haveAni(Integer.parseInt(aniid));
    }

    public static byte haveAni(int avatarid) {
        if (publicResAnis.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_FINAL;
        }
        if (publicOneRoomResAnis.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_ONEROOM;
        }
        if (tempResAnis.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_TEMP;
        } else {
            return -1;
        }
    }
    /*
     * 删除动画文件
     */

    public void deleteAvatar(String avatarid) {
    }
    /*
     * 赋值ani时返回true
     */

    public static boolean drawAnimation(Animation ani, int[] anim_status, Graphics g, int x, int y, boolean blcontinue) {
        if (ani == null) {
            return false;
        }
//          Tools.printLog("draw ani："+ani.iAnimationId);
//        //如果未load尝试取资源
        if (!ani.blHaveAni) {
//            if (BL_RECEIVE_NET_ANIMATION && havePublicAni(ani.iAnimationId)) {
            if (haveAni(ani.iAnimationId) != -1) {
                ani = getAnimation(ani.iAnimationId, haveAni(ani.iAnimationId));
                ani.blHaveAni = true;
                ani.show(g, x, y, anim_status, false, false);
                ani.nextFrame(anim_status, blcontinue ? true : false);
                return true;
            } else {
                return false;
            }
        } else {
            ani.show(g, x, y, anim_status, false, false);
            ani.nextFrame(anim_status, blcontinue ? true : false);
        }
        return false;
    }

    public static byte changeAction(Animation ani, int actionID, int pageID, int[] anim_status) {
        if (ani != null) {
            ani.changeAction(actionID, pageID, anim_status);
            return 2;
        }
        return 1;
    }

    public static boolean getHouseId(int id) {
        short[] aShort = new short[]{
            109,
            110,
            520,
            526,
            528,
            563,
            549,
            557,
            568,
            573,
            582,
            586,
            580,
            628,
            715,
            716,
            717,
            718,
            774,
            829,
            836,
            889,
            893,
            894,
            895,
            902,
            920,
            109,
            4,
            7,
            628,
            1298};
        for(int i = 0 ; i< aShort.length; i++)
        {
            if(id == aShort[i])
            {
                aShort = null;
                return true;
            }
        }
        aShort = null;
     return false;
    }

    /*********************************************************图片管理*************************************************************************/
    /*说明：
     * 在各界面的init方法里通过调用ResManager.createImage方法创建（无ID号图片比如半透明矩形图片不使用此方法保持原来的加载方式）
     *关于清理图片：无ID号图片在该界面的clear方法里设为null 有ID号的不用主动清理。各非漫游界面下图片资源类型为：RES_PUBLIC_TEMP 临时资源
     */
    /**
     *  创建一张图片池中的图片
     *  imgid 图片ID 
     *  type 图片类型：  RES_PUBLIC_FINAL 常驻内存资源； RES_PUBLIC_ONEROOM 在一个房间内常驻内存资源；RES_PUBLIC_TEMP 临时资源
     *  imgPath 图片路径
     *  blsend 本地没有时是否要从服务器请求
     *  alpha  带要改变透明度的图片 默认传入 -1
     */
    public static Image createImage(int imgid, byte type, String imgPath, boolean blsend, int alpha) {
        try {
            if(imgid == 1022)
                System.out.println(imgid);
            if (haveImage(imgid) != -1) {
                return getImage(imgid, haveImage(imgid));
            }
            //#if NOKIAN73
//#         if(getHouseId(imgid))
//#             alpha =  9999;
            //#else
            //#endif
            Image aImage = loadLocalImage(imgPath + imgid + ((imgPath.equals(Constant.RES_PATH)) ? ".bin" : ".png"), (imgPath.equals(Constant.RES_PATH)) ? alpha : 9999);
               if (aImage == null) {
                if (blsend) {
                    GameBean.SH_RES_PARAMETER_ONE = type;
                    GameBean.SH_RES_PARAMETER_TWO = imgid;
                    MainLogic.netController.setMsgResArray(new String[]{String.valueOf(imgid)});
                    MainLogic.netController.send(Constant.MSG_NET_GET_IMAGE, Constant.SOCKET_MSG_TYPE_RES);
                }
                return null;
            }
            putImage(type, imgid, aImage);
            return getImage(imgid, type);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return null;
    }

    public static Image createImage(int imgid) {
        return createImage(imgid, Constant.RES_PUBLIC_TEMP, Constant.RES_UI_PATH, false, -1);
    }
    /*
     * 从网络上获取图片
     */

    public static Image createImage(int imgid, byte type, byte[] aniStream) {
        try {
            if (imgid == -1 || aniStream == null) {
                return null;
            }
            if (haveImage(imgid) != -1) {
                return getImage(imgid, haveImage(imgid));
            }
            putImage(type, imgid, getImage(imgid, type, aniStream));
            return getImage(imgid, type);
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Image createImage(int imgid, byte type, byte[] aniStream, byte alhpa) {
        try {
            if (haveImage(imgid) != -1) {
                return getImage(imgid, haveImage(imgid));
            }
            putImage(type, imgid, getImage(imgid, alhpa, aniStream));
            return getImage(imgid, type);
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte haveImage(int avatarid) {
        if (publicResImgs.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_FINAL;
        }
        if (publicOneRoomResImgs.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_ONEROOM;
        }
        if (tempResImgs.containsKey(String.valueOf(avatarid))) {
            return Constant.RES_PUBLIC_TEMP;
        } else {
            return -1;
        }
    }

    public static Image getImage(int imgid, byte type) {
        if (type == -1) {
            type = haveImage(imgid);
        }
        switch (type) {
            case Constant.RES_PUBLIC_FINAL:
                return (Image) publicResImgs.get(String.valueOf(imgid));
            case Constant.RES_PUBLIC_ONEROOM:
                return (Image) publicOneRoomResImgs.get(String.valueOf(imgid));
            case Constant.RES_PUBLIC_TEMP:
                return (Image) tempResImgs.get(String.valueOf(imgid));
        }
        return null;
    }

    /**
     * 载入图片
     * @param path
     * @return
     */
    public static void putImage(byte type, int imgid, Image aImage) {
        try {
            if (imgid == -1 || aImage == null) {
                return;
            }
            switch (type) {
                case Constant.RES_PUBLIC_FINAL:
                    publicResImgs.put(String.valueOf(imgid), aImage);
                    break;
                case Constant.RES_PUBLIC_ONEROOM:
                    publicOneRoomResImgs.put(String.valueOf(imgid), aImage);
                    break;
                case Constant.RES_PUBLIC_TEMP:
                    tempResImgs.put(String.valueOf(imgid), aImage);
                    break;
            }
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }
    /*
     * 获得本地图片
     */

    public static Image loadLocalImage(String path, int alpha) {
        try {
            return getImage(path, alpha);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Image getImage(int imgid, byte type, byte[] aniStream) {
        try {
            if (aniStream == null || aniStream.length == 0) {
                return null;
            }
            Image tempImage = Image.createImage(aniStream, 0, aniStream.length);
            if (type == Constant.NET_TYPE_MAP_IMAGE_2) {
                return tempImage;
            }
            int width, height;
            width = tempImage.getWidth();
            height = tempImage.getHeight();
            int[] tempimgAni = new int[width * height];
            tempImage.getRGB(tempimgAni, 0, tempImage.getWidth(), 0, 0, width, height);
            tempimgAni = dealWithRgb(tempimgAni, -1);
            tempImage = null;
            return Image.createRGBImage(tempimgAni, width, height, true);
        } catch (Exception e) {
        }
        return null;
    }

    public static Image getImage(String path, int alpha) {
        try {
            Image img = Image.createImage(path);
            if (alpha == 9999) {
                return img;
            }
            int width, height;
            width = img.getWidth();
            height = img.getHeight();
            int length = width * height;
            int[] imgData = new int[length];
            if (alpha == -1) {
                img.getRGB(imgData, 0, img.getWidth(), 0, 0, width, height);
                imgData = dealWithRgb(imgData, -1);
                img = null;
                return Image.createRGBImage(imgData, width, height, true);
            } else {
                img.getRGB(imgData, 0, img.getWidth(), 0, 0, width, height);
                for (int i = 0; i < imgData.length; i++) {
                    imgData[i] &= 0x00FFFFFF;
                    if (imgData[i] != 0x00ff00ff) {
                        imgData[i] = imgData[i] | (alpha << 24);
                    }
                }
                return Image.createRGBImage(imgData, width, height, true);
            }

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return null;
    }

    public static int[] dealWithRgb(int[] tmpBuf, int rgb) {
        int r, g, b, tempr, k = 0;
        if (rgb != -1) {
            rgb &= 0x00FFFFFF;
            for (k = 0; k < tmpBuf.length; k++) {
                tmpBuf[k] &= 0x00FFFFFF;
                  //#if MOBILEID =="MOTO"
//#                 if ((tmpBuf[k]) == 16515324) {
//#                     tmpBuf[k] = tmpBuf[k] & 0x00ffffff;
//#                 }
                //#elif NORMAL_240_400
//#                 if ((tmpBuf[k]) == 16253176) {
//#                      tmpBuf[k] = tmpBuf[k] & 0x00ffffff;
//#                 }
                  //#else
                 if ((tmpBuf[k]) == 0x00ff00ff) {
                    tmpBuf[k] = tmpBuf[k] & 0x00ffffff;
                }
                  //#endif
            }
        } else {
            for (int i = 0; i < tmpBuf.length; i++) {
                //#if MOBILEID =="MOTO"
//#                 if ((tmpBuf[i] & 0x00ffffff) == 16515324) {
//#                     tmpBuf[i] = tmpBuf[i] & 0x00ffffff;
//#                 }
                //#elif NORMAL_240_400
//#                 if ((tmpBuf[i] & 0x00FFFFFF) == 16253176) {
//#                      tmpBuf[i] = tmpBuf[i] & 0x00ffffff;
//#                 }
                //#else
                 if ((tmpBuf[i] & 0x00ffffff) == 0x00ff00ff) {
                    tmpBuf[i] = tmpBuf[i] & 0x00ffffff;
                }
                //#endif
            }
        }
        return tmpBuf;
    }
    /*
     * 清楚制定类型和id的图片 
     * id : 图片的id;  type 资源类型 restype 为是图片还是动画文件
     */

    public static void clearRes(int id, int type, byte restype) {
        if (id == -1) {
            return;
        }
        if (restype == Constant.RES_TYPE_IMAGE) {
            switch (type) {
                case Constant.RES_PUBLIC_FINAL:
                    if (publicResImgs != null) {
                        publicResImgs.remove(String.valueOf(id));
                    }
                    break;
                case Constant.RES_PUBLIC_ONEROOM:
                    if (publicOneRoomResImgs != null) {
                        publicOneRoomResImgs.remove(String.valueOf(id));
                    }
                    break;
                case Constant.RES_PUBLIC_TEMP:
                    if (tempResImgs != null) {
                        tempResImgs.remove(String.valueOf(id));
                    }
                    break;
            }
        } else if (restype == Constant.RES_TYPE_ANI) {
            switch (type) {
                case Constant.RES_PUBLIC_FINAL:
                    if (publicResImgs != null) {
                        publicResImgs.remove(String.valueOf(id));
                    }
                    break;
                case Constant.RES_PUBLIC_ONEROOM:
                    if (publicOneRoomResAnis != null) {
                        publicOneRoomResAnis.remove(String.valueOf(id));
                    }
                    break;
                case Constant.RES_PUBLIC_TEMP:
                    if (tempResAnis != null) {
                        tempResAnis.remove(String.valueOf(id));
                    }
                    break;
            }
        }
    }

    public static void clearRes(int type) {
        try {
            switch (type) {
                case Constant.RES_PUBLIC_FINAL:
                    if (publicResAnis != null) {
                        publicResAnis.clear();
                    }
                    if (publicOneRoomResAnis != null) {
                        publicOneRoomResAnis.clear();
                    }
                    if (tempResAnis != null) {
                        tempResAnis.clear();
                    }
                    if (publicResImgs != null) {
                        publicResImgs.clear();
                    }
                    if (publicOneRoomResImgs != null) {
                        publicOneRoomResImgs.clear();
                    }
                    if (tempResImgs != null) {
                        tempResImgs.clear();
                    }
                    break;
                case Constant.RES_PUBLIC_ONEROOM:
                    if (publicOneRoomResAnis != null) {
                        publicOneRoomResAnis.clear();
                    }
                    if (publicOneRoomResImgs != null) {
                        publicOneRoomResImgs.clear();
                    }
                    break;
                case Constant.RES_PUBLIC_TEMP:
                    if (tempResAnis != null) {
                        tempResAnis.clear();
                    }
                    if (tempResImgs != null) {
                        tempResImgs.clear();
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.gc();
    }
}
